<template>
  <div class="contacts">
    <div class="outer-box">
      <div class="title">
        等待接入
      </div>
      <div v-if="Object.keys(contact.visitors).length > 0">
        <div class="contact" @click="addContact(item.visitorId)"
             v-for="(item,index) in contact.visitors" :key="index">
          <div class="avatar">
            <i class="el-icon-s-custom" />
          </div>
          <div class="box">
            <div class="name">{{item.name}}</div>
          </div>
        </div>
      </div>
      <div v-else class="empty">
        <div v-if="!contact.loadingVisitors">暂无</div>
        <div v-else>
          <i class="el-icon-loading"/>
        </div>
      </div>
    </div>
    <div class="outer-box">
      <div class="title">
        正在联系中
      </div>
      <div v-if="Object.keys(contact.contacts).length > 0">
        <div class="contact" :class="{active:selectContact === item.visitorId}"
             v-for="(item,index) in contact.contacts">
          <div class="avatar" @click="handleSelectContact(item.visitorId)">
            <i class="el-icon-phone animate-scale" v-if="item.callOffer"></i>
            <i class="el-icon-s-custom" v-else/>
          </div>
          <div class="box" @click="handleSelectContact(item.visitorId)">
            <div class="info">
              <div class="name">{{item.name}}</div>
              <div class="status" :class="[item.online == '1' ? 'online' : 'offline']">
                <div class="fill-circle"></div>
                <div class="status-text">{{item.online == '1' ? '在线' : '离线'}}</div>
              </div>
              <div class="date" v-if="item.latestMsgTime" v-text="getRelativeTime(item.latestMsgTime)"></div>
            </div>
            <div class="message">
              <div class="latest-msg"  v-text="item.latestMsg ? item.latestMsg : '~'"></div>
              <div class="new-msg-count" v-if="item.newMsgCount > 0" v-text="item.newMsgCount"></div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty">
        <div v-if="!contact.loadingContacts">暂无</div>
        <div v-else>
          <i class="el-icon-loading"/>
        </div>
      </div>
      <div class="visitor-test" @click="goToVisitorTestPage">访客测试</div>
    </div>
  </div>
</template>

<script>

import {sendMessage} from "@/api/im";
import {encodeContactMessage} from "@/modules/im/codec/encoder";
import Constants from "@/modules/im/constants";
import {getCurrentVisitors} from "@/api/im/visitor";
import {getCurrentContacts,acceptVisitor} from "@/api/im/contact";
import {getRelativeTime} from "@/libs/tools";
import config from "@/config";
import {addListener} from "@/modules/im/command/base";
import {rtcListeners} from "@/modules/im/command/listeners";
import {acceptCall} from "@/api/rtc/webrtc";

export default {
  name: "contact",
  data(){
    return {
      contact:{
        visitors:{},
        contacts:{},
        loadingVisitors:true,
        loadingContacts:true
      },
      selectContact: ''
    }
  },
  created() {
    let that = this
    addListener(rtcListeners,'Contact',function (content) {
      switch (content[Constants.Rtc.PROPERTY_CMD_TYPE]) {
        case 'offer':
          if(that.contact.contacts.hasOwnProperty(content[Constants.Rtc.PROPERTY_LOCAL])) {
            that.$set(that.contact.contacts[content[Constants.Rtc.PROPERTY_LOCAL]],'callOffer',content[Constants.Rtc.PROPERTY_PAYLOAD])
          }
          break
        default:
          break
      }
    })
    getCurrentVisitors().then(res => {
      if(res.code == 200) {
        let tmpObj = {}
        res.data.forEach(function (item) {
          tmpObj[item.visitorId] = item
        })
        that.$set(that.contact,'visitors',tmpObj)
      }
    }).finally(function (){
      that.contact.loadingVisitors = false
    })
    getCurrentContacts().then(res => {
      if(res.code == 200) {
        let tmpObj = {}
        res.data.forEach(function (item) {
          tmpObj[item.visitorId] = item
        })
        that.$set(that.contact,'contacts',tmpObj)
      }
    }).finally(function (){
      that.contact.loadingContacts = false
    })
  },
  methods:{
    goToVisitorTestPage(){
      let url = process.env.NODE_ENV === 'development' ? config.visitorTestUrl.dev : config.visitorTestUrl.pro
      url += '/#/service?tenantId=' + this.$store.state.userInfo.tenantId
      window.open(url)
    },
    getRelativeTime(obj){
      return getRelativeTime(obj,true)
    },
    handleContactMessage(obj){
      let cmd = obj[Constants.Contact.PROPERTY_CMD_TYPE]
      let payload = obj[Constants.Contact.PROPERTY_PAYLOAD]
      let tmpObj = {}
      switch (cmd) {
        case Constants.Contact.CMD_ADD_VISITOR:
          this.addVisitor(payload)
          break
        case Constants.Contact.CMD_REMOVE_VISITOR:
          this.removeVisitor(payload)
          break
        case Constants.Contact.CMD_REMOVE_CONTACT:
          this.removeContact(payload)
          break
        case Constants.Contact.CMD_ONLINE_NOTIFY:
          this.visitorStatusChange(payload,'1')
          break
        case Constants.Contact.CMD_OFFLINE_NOTIFY:
          this.visitorStatusChange(payload,'0')
          if(payload == this.selectContact) {
            this.$emit('handleSelectContactOffLine')
          }
          break
        default:
          break
      }
    },
    updateLatestMsg(visitorId,obj){
      if(visitorId && obj) {
        this.$set(this.contact.contacts[visitorId],'latestMsg',obj.msg)
        this.$set(this.contact.contacts[visitorId],'latestMsgTime',obj.date)
      }
    },
    handleChatMessage(msg) {
      let visitorId = ''
      if(this.contact.contacts.hasOwnProperty(msg.sender)) {
        visitorId = msg.sender
      }else if(this.contact.contacts.hasOwnProperty(msg.receiver)) {
        visitorId = msg.receiver
      }
      this.contact.contacts[visitorId].latestMsg = msg.msg
      this.contact.contacts[visitorId].latestMsgTime = msg.date
      if(this.selectContact != msg.sender && this.selectContact != msg.receiver) {
        this.contact.contacts[visitorId].newMsgCount += 1
      }
    },
    visitorStatusChange(vid,status){
      if(this.contact.contacts.hasOwnProperty(vid)) {
        this.contact.contacts[vid].online = status
      }else {
        this.removeVisitor(vid)
      }
    },
    removeVisitor(uid){
      this.$delete(this.contact.visitors,uid)
    },
    addVisitor(obj) {
      this.$set(this.contact.visitors,obj.visitorId,obj)
    },
    removeContact(uid) {
      this.$delete(this.contact.contacts,uid)
      if(Object.keys(this.contact.contacts).length == 0) {
        this.$emit('handleSelectContact',null)
      }
    },
    addContact(uid) {
      acceptVisitor(uid).then(res => {
        if(res.code == 200) {
          this.removeVisitor(uid)
          this.$set(this.contact.contacts,res.data.visitorId,res.data)
          this.handleSelectContact(uid)
        }
      })
    },
    handleSelectContact(uid){
      this.selectContact = uid
      this.contact.contacts[uid].newMsgCount = 0
      this.$emit('handleSelectContact',this.contact.contacts[uid])
    }
  }
}
</script>

<style scoped lang="less">
.contacts {
  position: relative;
  width: 200px;
  height: 100%;
  background: #FFF;
  overflow: hidden;
  overflow-y: auto;
  transition: width .3s;
  padding-bottom: 50px;
  box-sizing: border-box;

  &::-webkit-scrollbar {
    display: none;
  }
  .outer-box {
    width: 200px;

    &:first-child{
      border: 0;
    }

    .title {
      height: 30px;
      line-height: 30px;
      font-size: 12px;
      text-align: center;
      color: #666666;
    }
    .empty {
      height: 30px;
      line-height: 30px;
      text-align: center;
      font-size: 12px;
    }
    .contact {
      display: flex;
      align-items: center;
      position: relative;

      &.active,&:hover {
        background: #E8E8E8;
        position: relative;
        &:after{
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          bottom: 0;
          width: 2px;
          background: #409EFF;
        }
      }
      .avatar {
        height: 40px;
        font-size: 25px;
        padding: 0 10px;
        line-height: 40px;
        cursor: pointer;
        @keyframes scale-loop
        {
          0%{
            transform: scale(1);  /*开始为原始大小*/
          }
          25%{
            transform: scale(1.5); /*放大1.1倍*/
          }
          50%{
            transform: scale(1);
          }
          75%{
            transform: scale(1.5);
          }
        }
        .animate-scale {
          color: #0091ff;
          font-size: 20px;
          animation:scale-loop 2s infinite;
          -webkit-animation:scale-loop 2s infinite; /*Safari and Chrome*/
          animation-direction:alternate;/*轮流反向播放动画。*/
          animation-timing-function: ease-in-out; /*动画的速度曲线*/
          /* Safari 和 Chrome */
          -webkit-animation:scale-loop 2s infinite;
          -webkit-animation-direction:alternate;/*轮流反向播放动画。*/
          -webkit-animation-timing-function: ease-in-out; /*动画的速度曲线*/
        }
      }
      .box {
        flex: 1;
        box-sizing: border-box;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 10px 10px 10px 0;
        border-bottom: 1px solid #F0F0F0;
        cursor: pointer;

        .info {
          display: flex;
          align-items: center;

          .name {
            font-size: 14px;
            word-break: keep-all;
            text-overflow: ellipsis;
          }
          .status {
            display: flex;
            font-size: 12px;
            align-items: center;
            margin-left: 5px;
            width: 60px;

            .fill-circle {
              width: 6px;
              height: 6px;
              border-radius: 50%;
              margin: 0 2px;
            }
            &.online {
              color: #0091FF;
              .fill-circle{
                background: #0091FF;
              }
            }
            &.offline {
              color: #888888;
              .fill-circle{
                background: #888888;
              }
            }
          }
          .date {
            font-size: 12px;
            color: #888888;
          }
        }
        .message {
          position: relative;
          .latest-msg {
            font-size: 12px;
            height: 18px;
            line-height: 18px;
            overflow: hidden;
            color: #888888;
            white-space: nowrap;
            word-break: keep-all;
            text-overflow: ellipsis;
          }
          .new-msg-count {
            font-size: 15px;
            width: 20px;
            height: 20px;
            line-height: 20px;
            transform: scale(0.7);
            text-align: center;
            border-radius: 50%;
            position: absolute;
            right: -5px;
            top: 0;
            background: red;
            color: #FFF;
          }
        }
      }
    }
  }
  .visitor-test {
    font-size: 14px;
    height: 40px;
    line-height: 40px;
    color: #666666;
    text-decoration: underline;
    cursor: pointer;
    text-align: center;
    background: #FFFFFF;
    border-top: 1px solid #F0F0F0;
    &:hover{
      color: #0091ff;
    }
  }
}
</style>
